package cn.itsource.domain.org;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.itsource.basic.domain.BaseTreeNode;
import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableName;
import com.baomidou.mybatisplus.enums.FieldFill;
import com.baomidou.mybatisplus.enums.IdType;
import lombok.Data;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

//@Getter //相当于提供了get方法
//@Setter //相当于提供了set方法
@Data  //get set hashcode  equals toString
@TableName("t_department")
public class Department extends BaseTreeNode<Department> {
    //主键
    @TableId(value = "id", type = IdType.AUTO)
    private Long id;
    //说明
    //@NotBlank 不能为空
    @NotBlank(message = "当前编号不能为空")
    private String sn;
    //名字
    //@NotNull 不能为空
    @NotNull(message = "当前部门不能为空")
    private String name;
    //部门层级路径 /2/5/10 exist 是否被映射
    @TableField(value = "dir_path",exist = true)
    private String dirPath;
    //状态 （0：启动 -1 ：禁用）
    private Integer state;
    //没用
    @TableField(value = "manager_id",exist = true)
    private Long managerId;

    //部门经理
    @TableField(exist = false)
    private Employee manager;

    //没用
    private Long parentId;
//    @NotNull(message = "当前上级部门不能为空")
//    @Size(min = 1,message = "当前上级部门不能为空")
    @TableField(exist = false)
    private List<Long> parentIds;
    //父部门
    @TableField(exist = false)
    private Department parent;

    //子部门组
    @TableField(exist = false)
    private List<Department> children = new ArrayList<>();

    public List<Long> getParentIdsView(){
        if (StrUtil.isBlank(this.dirPath)) return null;
        return Arrays.asList(this.dirPath.split("/"))
                .stream().map(s -> Long.parseLong(s)).collect(Collectors.toList());

    }

    //初始化参数
    public  void init(){
        //1.取出parentIds集合
        List<Long> parentIds = this.getParentIds();
        //List<Integer> collect = parentIds.stream().map(aLong -> aLong.intValue()).collect(Collectors.toList());
        //判断集合是否为空
        if (CollectionUtil.isEmpty(parentIds)) return;
        //2.获取最后一个元素
        Long parentId = parentIds.get(parentIds.size() - 1);
        //3.赋值到parentID属性中
        this.setParentId(parentId);
        this.setState(1);
        //[1,2,3] 想要的结果 : 1/2/3
        String replace = parentIds.toString().
                replace("[", "").
                replace("]", "").
                replace(",", "/").
                replace(" ","");
        this.setDirPath(replace);
    }

}
